<template>
  <div class="chat-panel">
    <!-- 响应内容区域 -->
    <div class="response-area">
      <div v-if="!currentResponse && !isLoading" class="empty-state">
        <el-empty description="请输入您的项目需求描述，AI将帮您生成详细项目说明">
          <!-- <el-button type="primary" size="large" @click="focusInput" class="action-button">
            <el-icon>
              <ChatLineRound />
            </el-icon>
            <span>开始对话</span>
          </el-button> -->
        </el-empty>
      </div>

      <div v-else-if="isLoading" class="loading-state">
        <div class="loading-animation">
          <el-icon class="loading-icon">
            <Loading />
          </el-icon>
          <span>AI 正在思考中...</span>
        </div>
        <el-skeleton :rows="10" animated class="loading-skeleton" />
      </div>

      <div v-else class="response-content">
        <!-- 需求分析阶段 -->
        <div v-if="currentStep === 'requirement'">
          <div class="step-progress">
            <el-steps :active="1" finish-status="success" align-center>
              <el-step title="需求分析">
                <template #icon>
                  <el-icon>
                    <Document />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="工作流结构" @click="changeStep('workflow')">
                <template #icon>
                  <el-icon>
                    <Connection />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="代码生成" @click="changeStep('code')">
                <template #icon>
                  <el-icon>
                    <Notebook />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="部署指南" @click="changeStep('deploy')">
                <template #icon>
                  <el-icon>
                    <Promotion />
                  </el-icon>
                </template>
              </el-step>
            </el-steps>
          </div>
          <div class="response-header">
            <div class="header-title">
              <el-icon class="header-icon">
                <Document />
              </el-icon>
              <h2>项目需求分析</h2>
            </div>
            <div class="actions">
              <el-tooltip content="编辑需求" placement="top">
              </el-tooltip>
              <el-button type="success" size="small" class="action-button" @click="generateWorkflow"
                v-if="!isEditing && historyStore.currentWorkflow == null">
                <el-icon>
                  <Check />
                </el-icon>
                <span>确认并生成工作流</span>
              </el-button>
            </div>
          </div>

          <div class="markdown-section">
            <FuncsDisplay class="funcs-display"></FuncsDisplay>
          </div>
        </div>

        <!-- 工作流阶段 -->
        <div v-else-if="currentStep === 'workflow'">
          <div class="step-progress">
            <el-steps :active="2" finish-status="success" align-center>
              <el-step title="需求分析" @click="changeStep('requirement')">
                <template #icon>
                  <el-icon>
                    <Document />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="工作流结构">
                <template #icon>
                  <el-icon>
                    <Connection />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="代码生成" @click="changeStep('code')">
                <template #icon>
                  <el-icon>
                    <Notebook />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="部署指南" @click="changeStep('deploy')">
                <template #icon>
                  <el-icon>
                    <Promotion />
                  </el-icon>
                </template>
              </el-step>
            </el-steps>
          </div>

          <workflow-display :workflow="currentWorkflow" displayMode="json" />

          <div class="action-buttons" v-if="historyStore.currentCode === ''">
            <el-button type="primary" size="large" class="action-button" @click="generateCode" :loading="isLoading">
              <el-icon>
                <Notebook />
              </el-icon>
              <span>生成代码</span>
            </el-button>
          </div>
        </div>

        <!-- 代码生成阶段 -->
        <div v-else-if="currentStep === 'code'">
          <div class="step-progress">
            <el-steps :active="3" finish-status="success" align-center>
              <el-step title="需求分析" @click="changeStep('requirement')">
                <template #icon>
                  <el-icon>
                    <Document />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="工作流结构" @click="changeStep('workflow')">
                <template #icon>
                  <el-icon>
                    <Connection />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="代码生成">
                <template #icon>
                  <el-icon>
                    <Notebook />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="部署指南" @click="changeStep('deploy')">
                <template #icon>
                  <el-icon>
                    <Promotion />
                  </el-icon>
                </template>
              </el-step>
            </el-steps>
          </div>
          <CodesDisplay></CodesDisplay>
          <div class="action-buttons">
            <el-button type="primary" size="large" class="action-button" @click="generateDeployGuide"
              :loading="isLoading" v-if="historyStore.currentDeployGuide == ''">
              <el-icon>
                <Promotion />
              </el-icon>
              <span>查看部署指南与代码下载</span>
            </el-button>
          </div>
        </div>

        <!-- 部署指南阶段 -->
        <div v-else-if="currentStep === 'deploy'">
          <div class="step-progress">
            <el-steps :active="4" finish-status="success" align-center>
              <el-step title="需求分析" @click="changeStep('requirement')">
                <template #icon>
                  <el-icon>
                    <Document />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="工作流结构" @click="changeStep('workflow')">
                <template #icon>
                  <el-icon>
                    <Connection />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="代码生成" @click="changeStep('code')">
                <template #icon>
                  <el-icon>
                    <Notebook />
                  </el-icon>
                </template>
              </el-step>
              <el-step title="部署指南">
                <template #icon>
                  <el-icon>
                    <Promotion />
                  </el-icon>
                </template>
              </el-step>
            </el-steps>
          </div>
          <MarkdownRenderer :content="currentDeployGuide"></MarkdownRenderer>


          <div class="action-buttons">
            <el-button type="success" size="large" class="action-button" @click="donwloadProjectData">
              <el-icon>
                <Plus />
              </el-icon>
              <span>下载项目文件</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域，仅在初始状态或需求阶段显示 -->
    <div class="input-area" v-if="!currentResponse || currentStep === 'initial'">
      <el-input v-model="promptInput" type="textarea" :rows="3" placeholder="描述您的项目需求..." resize="none" ref="inputRef"
        @keydown.ctrl.enter="submitPrompt" class="prompt-input" />
      <div class="input-actions">
        <div class="input-hint">
          <el-icon>
            <InfoFilled />
          </el-icon>
          <span class="hint">按 Ctrl+Enter 提交</span>
        </div>
        <el-button type="primary" :loading="isLoading" @click="submitPrompt" :disabled="!promptInput.trim()"
          class="submit-button">
          <el-icon>
            <Position />
          </el-icon>
          <span>提交需求</span>
        </el-button>
      </div>
    </div>
  </div>

  <!-- 需求编辑抽屉 -->
  <requirement-editor v-model="showRequirementEditor" :content="currentResponse" @confirm="handleRequirementUpdate" />
</template>

<script setup>
import { ref, computed } from 'vue';
import { useHistoryStore } from '@/stores/history';
import RequirementEditor from '@/components/RequirementEditor.vue';
import WorkflowDisplay from '@/components/WorkflowDisplay.vue';
import CodesDisplay from './CodesDisplay.vue';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';
import FuncsDisplay from './FuncsDisplay.vue';
import { ElMessage } from 'element-plus';

import {
  Document,
  Edit,
  Check,
  Connection,
  Notebook,
  Promotion,
  Plus,
  Position,
  InfoFilled,
  Loading,
  ChatLineRound
} from '@element-plus/icons-vue';

// 接收的属性
const props = defineProps({
  isLoading: {
    type: Boolean,
    default: false
  }
});

// 向父组件触发的事件
const emit = defineEmits(['submit-prompt', 'update:isLoading']);

// Store
const historyStore = useHistoryStore();

// 本地状态
const promptInput = ref('');
const inputRef = ref(null);
const isEditing = ref(false);
const showRequirementEditor = ref(false);
// 计算属性 - 从 Store 中获取状态
const currentResponse = computed(() => historyStore.currentResponse);
const currentWorkflow = computed(() => {
  const workflow = historyStore.currentWorkflow;
  // 确保返回有效的对象，不是undefined或null
  if (!workflow) return null;

  // 如果是字符串，尝试解析为对象
  if (typeof workflow === 'string') {
    try {
      return JSON.parse(workflow);
    } catch (e) {
      console.error('工作流解析错误:', e);
      return {};
    }
  }

  return workflow;
});

const currentDeployGuide = computed(() => {
  const guide = historyStore.currentDeployGuide;
  if (!guide) return '';

  // 如果是对象，转换为字符串
  if (typeof guide === 'object') {
    try {
      return JSON.stringify(guide, null, 2);
    } catch (e) {
      console.error('部署指南序列化错误:', e);
      return '';
    }
  }

  return guide;
});
const currentStep = computed(() => historyStore.currentStep);

const changeStep = (step) => {
  if (props.isLoading) return; // 如果正在加载，禁止切换步骤
  if (step === 'requirement' && currentResponse.value != '') {
    historyStore.currentStep = 'requirement';
  } else if (step === 'workflow' && currentWorkflow.value != null) {
    historyStore.currentStep = 'workflow';
  }
  else if (step === 'code' && historyStore.currentCode != '') {
    historyStore.currentStep = 'code';
  }
  else if (step === 'deploy' && currentDeployGuide.value != '') {
    historyStore.currentStep = 'deploy';
  }

};

// 处理需求更新
const handleRequirementUpdate = async (updatedRequirement) => {
  try {
    emit('update:isLoading', true);
    console.log('更新需求开始', updatedRequirement);
    await historyStore.submitRequirement(updatedRequirement);
    console.log('更新需求完成');
  } catch (error) {
    console.error('更新需求失败:', error);
    ElMessage.error('更新需求失败: ' + error.message);
  } finally {
    emit('update:isLoading', false);
  }
};

// 生成工作流
const generateWorkflow = async () => {
  try {
    emit('update:isLoading', true);
    console.log('生成工作流开始', currentResponse.value);
    await historyStore.submitRequirement(currentResponse.value);
    console.log('生成工作流完成');
  } catch (error) {
    console.error('生成工作流失败:', error);
    ElMessage.error('生成工作流失败: ' + error.message);
  } finally {
    emit('update:isLoading', false);
  }
};

// 生成代码
const generateCode = async () => {
  try {
    emit('update:isLoading', true);

    console.log('生成代码开始', currentWorkflow.value);
    await historyStore.submitWorkflow();
    console.log('生成代码完成');
  } catch (error) {
    console.error('生成代码失败:', error);
    ElMessage.error('生成代码失败: ' + error.message);
  } finally {
    emit('update:isLoading', false);
  }
};

// 生成部署指南
const generateDeployGuide = async () => {
  try {
    emit('update:isLoading', true);
    await historyStore.submitCodeForDeployGuide();
  } catch (error) {
    ElMessage.error('生成部署指南失败: ' + error.message);
  } finally {
    emit('update:isLoading', false);
  }
};

// 创建新项目
const createNewProject = () => {
  historyStore.createNewChat();
  promptInput.value = '';
};

// 提交提示词
const submitPrompt = async () => {
  if (!promptInput.value.trim() || props.isLoading) return;

  try {
    emit('update:isLoading', true);
    await historyStore.submitPrompt(promptInput.value);
    promptInput.value = ''; // 清空输入
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message);
  } finally {
    emit('update:isLoading', false);
  }
};


async function donwloadProjectData() {
  const url = await historyStore.getAllFile()
}


</script>

<style scoped>
.funcs-display {
  max-height: 100%;
  /* 确保子元素不超过父容器的高度 */
  overflow-y: auto;
  /* 垂直方向溢出时显示滚动条 */
}

.chat-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #f8fafc;
}

.response-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.empty-state,
.loading-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  padding: 40px;
}

.loading-state {
  padding: 40px;
}

.loading-animation {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
  color: #409eff;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 12px;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-skeleton {
  width: 100%;
  max-width: 800px;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #409eff;
}

.response-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
  font-weight: 600;
}

.response-content {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.response-content:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

/* 对于宽屏，设置较大内容区域的最大宽度，让内容居中 */
@media (min-width: 1600px) {
  .response-content {
    width: 90%;
    max-width: 1600px;
  }
}

.markdown-section {
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #ebeef5;
}

.input-area {
  padding: 20px 24px;
  border-top: 1px solid #ebeef5;
  background-color: white;
  width: 100%;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.prompt-input {
  border-radius: 8px;
  overflow: hidden;
}

.prompt-input :deep(.el-textarea__inner) {
  resize: none;
  min-height: 80px;
  padding: 16px;
  font-size: 16px;
  border-radius: 8px;
  box-shadow: inset 0 0 0 1px #dcdfe6;
  transition: box-shadow 0.3s ease, border-color 0.3s ease;
}

.prompt-input :deep(.el-textarea__inner:focus) {
  box-shadow: inset 0 0 0 1px #409eff, 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-hint {
  display: flex;
  align-items: center;
  color: #909399;
}

.input-hint .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.hint {
  color: #909399;
  font-size: 14px;
}

.submit-button {
  padding: 12px 24px;
  font-size: 16px;
}

/* 步骤进度条 */
.step-progress {
  margin-bottom: 30px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  gap: 16px;
}

.actions {
  display: flex;
  gap: 12px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  font-size: 16px;
  transition: transform 0.2s ease;
}

.action-button:hover {
  transform: translateY(-2px);
}

.action-icon-button {
  display: flex;
  align-items: center;
  gap: 6px;
}
</style>